#import "AppDelegate.h"
#import "ScreenAdapter.h"
#import "WelcomeViewController.h"
#import "DBManager.h"
#import "Constants.h"
#import "RegLoginViewController.h"
#import "MainViewCreater.h"
#import "UserDao.h"
#import "RequestServerAPI.h"
#import "ReloginWaitingViewController.h"
#import "BabyInfoViewController.h"
#import "JoinClassViewController.h"
#import "Reachability.h"
#import "IQKeyboardManager.h"
#import "AllBaseViewController.h"
#import "MobClick.h"
#import "MMLocationManager.h"
#import "UMSocial.h"
#import "UMFeedback.h"
#import "AppDelegate+EaseMob.h"
#import "AppDelegate+Parse.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"

@interface AppDelegate ()

@property(retain,nonatomic) UIViewController *viewController;
@end

@implementation AppDelegate
@synthesize viewController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    _connectionState = eEMConnectionConnected;
    [MobClick startWithAppkey:@"55a73f3a67e58e7b700001c9" reportPolicy:BATCH channelId:nil];
    [UMSocialData setAppKey:@"55a73f3a67e58e7b700001c9"];
    [UMSocialWechatHandler setWXAppId:@"wx83f39e7d8c1c84e5" appSecret:@"0c58cfb3f5a36334d59d86c07245e80a" url:@"http://www.zgyxyl.com"];
    [UMSocialQQHandler setQQWithAppId:@"1104806844" appKey:@"EejMkScfolxi8c5s" url:@"http://www.zgyxyl.com"];
    [UMFeedback setAppkey:@"55a73f3a67e58e7b700001c9"];
    [UMSocialConfig hiddenNotInstallPlatforms:@[UMShareToQQ,UMShareToQzone,UMShareToWechatSession,UMShareToWechatTimeline]];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loginStateChange:)
                                                 name:KNOTIFICATION_LOGINCHANGE
                                               object:nil];

    //创建jyb.db数据库
    [[DBManager getInstanse]createDataBaseWithName:@"jyb"];
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    //创建数据表
    NSArray *tableArray = [[[Constants alloc]init] getCreateTableCmdArray];
    for (NSString *createCmdString in tableArray) {
        //创建数据库中的表
        [[DBManager getInstanse]createTable:createCmdString];
    }
    
    //初始化SPLASH_VERSION数据表单
    NSArray *result = [[DBManager getInstanse]selectFrom:@"SPLASH_VERSION" items:[NSArray arrayWithObjects:@"*", nil] limits:@"1"];
    if (result.count == 0) {//当闪屏表中不存在数据的时候，初始化表单version值为0
        NSDictionary *db_dict = [NSDictionary dictionaryWithObject:@"0" forKey:@"version"];
        [[DBManager getInstanse]insertTo:@"SPLASH_VERSION" dictionary:db_dict];
    }
    [[IQKeyboardManager sharedManager] setEnable:YES];
    [[IQKeyboardManager sharedManager] disableToolbarInViewControllerClass:[AllBaseViewController class]];
    [[IQKeyboardManager sharedManager] disableInViewControllerClass:[AllBaseViewController class]];
    
    [self easemobApplication:application didFinishLaunchingWithOptions:launchOptions];
    
    // 环信UIdemo中有用到Parse，您的项目中不需要添加，可忽略此处。
    [self parseApplication:application didFinishLaunchingWithOptions:launchOptions];
    
    
    [self loginStateChange:nil];
    
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    //检查是否需要闪屏宣传页
    [self checkSplashView];
    
   // UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];

    self.window.rootViewController = viewController;
    [self.window makeKeyAndVisible];
    
    //定义导航条的颜色
    [[UINavigationBar appearance] setBarTintColor:NavigationColor];
    if (false == IS_LOW_IOS8) {
        [[UINavigationBar appearance] setTranslucent:NO];
    }
    
    //定义导航条上文字的颜色
    [[UINavigationBar appearance] setTintColor:DefaultNavigationColor];
    
    _Status_Gap = (Current_device_vesion >= 7.0) ? 20 : 0;
    _NavHeight = _Status_Gap + CUSTOM_NAV_HEIGHT;
//    ContentStartPointY = (Current_device_vesion >= 7.0) ? 64 : 0;
    
    CGFloat inch = [UIUtils applicationSreenInch];
    if (inch == 5.5) {
        _AppScreenInchType1 = AppScreenInch5_5;
    }else if (inch == 4.7) {
        _AppScreenInchType1 = AppScreenInch4_7;
    }else if (inch == 4.0) {
        _AppScreenInchType1 = AppScreenInch4_0;
    }else {
        _AppScreenInchType1 = AppScreenInch3_5;
    }
    
    //实时监控网络
    [NOTIFICATION_CENTER addObserver:self
                            selector:@selector(reachabilityChanged:)
                                name:kReachabilityChangedNotification
                              object:nil];
    [self checkNetwork];

    
    //设置导航的标题的颜色
    NSShadow *shadow = [[NSShadow alloc] init];
    shadow.shadowColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8];
    shadow.shadowOffset = CGSizeMake(0, 1);
    [[UINavigationBar appearance] setTitleTextAttributes: @{NSForegroundColorAttributeName : NavigationTitleColor,
                                                            NSFontAttributeName:[UIFont systemFontOfSize:22.0]
                                                            }];
    [[MMLocationManager shareLocation] getLocationCoordinate:^(CLLocationCoordinate2D locationCorrrdinate) {
        debugLog(@"lat:%f,lng:%f",locationCorrrdinate.latitude,locationCorrrdinate.longitude);
    } withAddress:^(NSString *addressString) {
        debugLog(@"\naddressString:%@",addressString);
    }];
    
    

    return YES;
}

#pragma mark - private
//登陆状态改变
-(void)loginStateChange:(NSNotification *)notification
{
    UINavigationController *nav = nil;
    
    BOOL isAutoLogin = [[[EaseMob sharedInstance] chatManager] isAutoLoginEnabled];
    BOOL loginSuccess = [notification.object boolValue];
    
    if (isAutoLogin || loginSuccess) {//登陆成功加载主窗口控制器
        //加载申请通知的数据
        [[ApplyViewController shareController] loadDataSourceFromLocalDB];
//        if (_mainController == nil) {
//            _mainController = [[MainViewController alloc] init];
//            [_mainController networkChanged:_connectionState];
//            nav = [[UINavigationController alloc] initWithRootViewController:_mainController];
//        }else{
//            nav  = _mainController.navigationController;
//        }
        
        // 环信UIdemo中有用到Parse，您的项目中不需要添加，可忽略此处。
        //[self initParse];
    }else{//登陆失败加载登陆页面控制器
//        _mainController = nil;
//        LoginViewController *loginController = [[LoginViewController alloc] init];
//        nav = [[UINavigationController alloc] initWithRootViewController:loginController];
//        loginController.title = NSLocalizedString(@"AppName", @"EaseMobDemo");
        
        // 环信UIdemo中有用到Parse，您的项目中不需要添加，可忽略此处。
        //[self clearParse];
    }
    
    //设置7.0以下的导航栏
    /*
    if ([UIDevice currentDevice].systemVersion.floatValue < 7.0){
        nav.navigationBar.barStyle = UIBarStyleDefault;
        [nav.navigationBar setBackgroundImage:[UIImage imageNamed:@"titleBar"]
                                forBarMetrics:UIBarMetricsDefault];
        
        [nav.navigationBar.layer setMasksToBounds:YES];
    }
    
    self.window.rootViewController = nav;
    
    [nav setNavigationBarHidden:YES];
    [nav setNavigationBarHidden:NO];
     */
}


- (void)checkNetwork {
    Reachability * reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
    
    reach.unreachableBlock = ^(Reachability * reachability)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self ShowExclaHud:@"网络不给力，请检查网络！"];
        });
    };
    [reach startNotifier];
}

#pragma mark - MBProgressHUD
- (void)ShowExclaHud:(NSString *)title{
    if(_hud == nil) {
        _hud = [MBProgressHUD showHUDAddedTo:self.window animated:YES];
    }
    [self showHudComplete:title success:NO];
}

- (void)showHudComplete:(NSString *)title success:(BOOL)success {
    NSString *name = success ? @"success" : @"excla";
    _hud.dimBackground = NO;
    _hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:name]];
    _hud.mode = MBProgressHUDModeCustomView;
    if(title.length > 0) {
        _hud.labelText = title;
    }
    [_hud performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:2];
}
/**
 检查是否显示宣传图
 如果某次版本更新，可以修改constants.h文件中的SPLASH_VERSION,让其+1就可以显示了。
 */
- (void)checkSplashView{
    NSArray *arr = [[DBManager getInstanse] selectFrom:@"SPLASH_VERSION" items:[NSArray arrayWithObjects:@"version", nil] limits:@"1"];
    //判断宣传图Splash的显示与否
    NSString *splashVersion = [[arr objectAtIndex:0]objectAtIndex:0];
    
    if (splashVersion == nil || [splashVersion integerValue] < SPLASH_VERSION) {  //本地版本号小于应用的更新后版本号，展示SPLASH
        //首次进入app或者有新版本的Splash，将当前版本的应用版本号写入DB。
        NSString *str = [NSString stringWithFormat:@"%d",SPLASH_VERSION];
        NSDictionary *db_dict = [NSDictionary dictionaryWithObject:str forKey:@"version"];
        [[DBManager getInstanse] updateTable:@"SPLASH_VERSION" updateDict:db_dict limits:@"1"];
        //显示Splash
        viewController = [[WelcomeViewController alloc] initWithNibName:nil bundle:nil];
    }else{
        //此处需要判断用户是否已经登录，登录的用户不需要再次进入注册登录界面
        //初始化用户信息表
        
        /*
        if (![[UserDao getInstance]hasLogin]) {//用户未登录 进入登录注册界面
            //进入登录注册页面
            viewController = [[RegLoginViewController alloc]init];
        }else{  //用户已经登录
            //存在多用户的情况，但仅有一个用户的数据的hasLogin值是1（表示登录）
            if (![[UserDao getInstance]hasLogin]) {
                viewController = [[RegLoginViewController alloc]init];
            }else{
              //存在已经登录的用户
                ReloginWaitingViewController* rwViewController =  [[ReloginWaitingViewController alloc]init];
                rwViewController.user_id =[NSString stringWithFormat:@"%ld", [[UserDao getInstance]getUserId]];
                rwViewController.user_type = @"1";
                rwViewController.user_token = [[UserDao getInstance]getAccessToken];
                viewController = rwViewController;
            }
        }
         */
        //无论是否登录，直接进入主页
        //UIViewController *mainViewController = [[MainViewCreater getInstance]createMainView];
        TabViewController *mainViewController = [[TabViewController alloc] init];
        
        viewController = mainViewController;
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    timeStamp = [[NSString stringWithFormat:@"%ld", (long)[[NSDate  date] timeIntervalSince1970]] integerValue];
    timeStamp  = -timeStamp;
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    timeStamp += [[NSString stringWithFormat:@"%ld", (long)[[NSDate  date] timeIntervalSince1970]] integerValue];
    NSLog(@"time gap: %ld",timeStamp);
    if (timeStamp > 10) {
        welImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, [ScreenAdapter getInstanse].screenWidth, [ScreenAdapter getInstanse].screenHeight)];
        [welImgView setImage:[UIImage imageNamed:@"launch.png"]];
        //屏蔽底层的点击响应
        welImgView.userInteractionEnabled = YES;
        
        //图片不出现缩放拉伸变形的代码
        [welImgView setContentScaleFactor:[[UIScreen mainScreen] scale]];
        welImgView.contentMode =  UIViewContentModeScaleAspectFill;
        welImgView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        welImgView.clipsToBounds  = YES;
        
        [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(removeImage) userInfo:nil repeats:NO];
        [self.window.rootViewController.view addSubview:welImgView];
    }
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
//    if (_mainController) {
//        [_mainController jumpToChatList];
//    }
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
//    if (_mainController) {
//        [_mainController didReceiveLocalNotification:notification];
//    }
}


-(NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
    return UIInterfaceOrientationMaskPortrait;
}

//实时监控网络状况
-(void)reachabilityChanged:(NSNotification*)note {
    Reachability * reach = [note object];
    
    _appNetworkStatus = reach.currentReachabilityStatus;
    if(_appNetworkStatus == NotReachable) {
        [self ShowExclaHud:@"网络不给力，请检查网络！"];
    }else {
        [_hud removeFromSuperview];
        _hud = nil;
    }
    [NOTIFICATION_CENTER postNotificationName:kNetworkStateChangedNotification
                                       object:self];
}

-(void)removeImage{
    [welImgView removeFromSuperview];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
//    [UMessage registerDeviceToken:deviceToken];
//    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
//    NSString *deviceToken1 = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
//    
//    NSLog(@"deviceToken:%@", deviceToken1);
//    self.deviceToken = deviceToken1;
//    
//    NSString *path = [NSString stringWithFormat:@"%@%@",kBaseUrl,kMemberDevice];
//    NSDictionary *para = @{@"uid":@([[Config Instance]getUID]),@"device_token":deviceToken1};
//    [[AFOSCClient sharedClient]getPath:path parameters:para success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        
//    }];
    
    //这里可以把deviceToken发给自己的服务器
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [UMSocialSnsService handleOpenURL:url];
}
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    return  [UMSocialSnsService handleOpenURL:url];
}
@end
